package com.easpeed.comon.ui

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log;
import com.bigyu.utils.Logger
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.mapapi.map.offline.MKOLSearchRecord
import com.baidu.mapapi.map.offline.MKOLUpdateElement
import com.baidu.mapapi.map.offline.MKOfflineMap
import com.baidu.mapapi.map.offline.MKOfflineMapListener
import com.easpeed.comon.utils.CacheHelper.Companion.instance
import com.easpeed.comon.utils.CommonOperateUtils.moveToClearTask
import com.easpeed.comon.utils.SocketHelper.stopSocket
import com.easpeed.elevator.R
import com.easpeed.elevator.databinding.ActivityOfflineMapBinding
import com.easpeed.elevator.utils.WwAdapter
import com.easpeed.elevator.utils.WwViewHolder
import com.easpeed.user.UserBaseActivity
import com.easpeed.user.UserLoginActivity
import com.easpeed.user.dialog.UserDialogHelper.showNoticeDialog


class OfflineMapActivity : UserBaseActivity() {
    var binding: ActivityOfflineMapBinding? = null
    var mOffline: MKOfflineMap = MKOfflineMap()


    private val downloadMap = mutableMapOf<Int, Int>()

    override fun initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_offline_map)
        mOffline.init(object : MKOfflineMapListener {
            @SuppressLint("NotifyDataSetChanged")
            override fun onGetOfflineMapState(type: Int, state: Int) {
                Logger.e("TAG", "onGetOfflineMapState: $type, $state")

                when (type) {
                    MKOfflineMap.TYPE_DOWNLOAD_UPDATE -> {
                        // 获取更新的城市状态
                        val update: MKOLUpdateElement = mOffline.getUpdateInfo(state)
                        Logger.d("下载进度", update.cityName + "   ${update.cityID}：" + update.ratio + "%")

                        downloadMap[update.cityID] = update.ratio

                        adapterEvent?.notifyDataSetChanged()
                    }

                    MKOfflineMap.TYPE_NEW_OFFLINE -> Logger.d("离线地图", "添加了新的离线地图包")
                    MKOfflineMap.TYPE_VER_UPDATE -> Logger.d("离线地图", "离线地图更新了")
                    else -> {

                    }
                }

            }
        });
        initRecyclerView(binding?.recylerview)

        val offlineCityList = mOffline.offlineCityList
        // 获取所有已下载（或正在下载）的离线地图信息
        val updateList = mOffline.allUpdateInfo

        if (updateList != null) {
            for (element in updateList) {
                downloadMap[element.cityID] = element.ratio
                Logger.d("离线地图", "城市：" + element.cityName +
                        "，进度：" + element.ratio + "%" +
                        "，状态：" + element.status)
            }
        }
        offlineCityList?.forEach {
            if (it.childCities == null) {
                cityList.add(it)
//                mOffline.remove(it.cityID);
            } else {
                it.childCities?.forEach {
                    cityList.add(it)
//                    mOffline.remove(it.cityID);
                }
            }
        }
        adapterEvent?.notifyDataSetChanged()


    }


    var adapterEvent: WwAdapter<MKOLSearchRecord>? = null
    private val cityList = mutableListOf<MKOLSearchRecord>()

    private fun initRecyclerView(recyclerView: RecyclerView?) {
        adapterEvent = object : WwAdapter<MKOLSearchRecord>() {
            override fun initRecyclerView(mContext: Context, adapter: WwAdapter<MKOLSearchRecord>) {
                val manager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
                recyclerView?.layoutManager = manager
                recyclerView?.adapter = adapter
            }

            override fun getLayoutId(): Int {
                return R.layout.item_city_info
            }

            override fun convert(viewHolder: WwViewHolder, bean: MKOLSearchRecord, position: Int) {
                viewHolder.setText(R.id.name, bean.cityName)

                downloadMap[bean.cityID]?.let {

                    if (it >= 100) {
                        viewHolder.setText(R.id.download, "已下载")
                    } else {
                        viewHolder.setText(R.id.download, "下载中：${it.toString()}%")
                    }
                }

                viewHolder.setOnClickListener(R.id.download) {
                    val radio = downloadMap[bean.cityID] ?: 0
                    if (radio >= 100) {
                        Logger.e("TAG", "convert: 已下载")
                        return@setOnClickListener
                    }
                    downloadMap[bean.cityID] = 0
                    mOffline.start(bean.cityID)

                    adapterEvent?.notifyDataSetChanged()
                }

                viewHolder.setOnLongClickListener(R.id.download) {
                    val radio = downloadMap[bean.cityID] ?: 0
                    if (radio <= 0 ){
                        return@setOnLongClickListener false
                    }
                    showNoticeDialog(mContext, "提示", "确定删除${bean.cityName}吗？", {
                        mOffline.remove(bean.cityID)
                        downloadMap.remove(bean.cityID)
                        adapterEvent?.notifyDataSetChanged()
                    }) { }
                    false
                }
            }
        }.create(mContext, cityList)
    }

    override fun onPause() {
        super.onPause()
    }
}